package cn.wolfcode.ssm.service.impl;

import cn.wolfcode.ssm.domain.Activity;
import cn.wolfcode.ssm.domain.ActivityItem;
import cn.wolfcode.ssm.mapper.ActivityItemMapper;
import cn.wolfcode.ssm.mapper.ActivityMapper;
import cn.wolfcode.ssm.qo.QueryObject;
import cn.wolfcode.ssm.service.IActivityService;
import cn.wolfcode.ssm.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ActivityServiceImpl implements IActivityService {

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ActivityItemMapper activityItemMapper;


    @Override
    public Long save(Activity activity,Long activityItemId) {
        List<ActivityItem> activityItems = activityItemMapper.selectBActivityId(activity.getId());
        activityItems.forEach(activityItem -> {
            Long id = activityItem.getId();
            if(id.equals(activityItemId)){
                Integer num = activityItem.getNum() + 1;
                //将集合中的数据更改并返回
                activityItem.setNum(num);
                //票数加一
                activityItemMapper.updateNumById(id,num);
            }
        });
        Long employeeId = UserContext.getEmployee().getId();
        //员工选的选项插入中间表choice
        activityMapper.insertChoice(employeeId,activityItemId,new Date());
        return activity.getId();

    }

    @Override
    public void delete(Long id) {
        activityMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Activity activity) {
        activityMapper.updateByPrimaryKey(activity);
    }

    @Override
    public Activity get(Long id) {
        return activityMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Activity> listAll() {
        return activityMapper.selectAll();
    }

    @Override
    public PageInfo<Activity> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); //对下一句sql进行自动分页
        List<Activity> activitys = activityMapper.selectForList(qo); //里面不需要自己写limit
        return new PageInfo<Activity>(activitys);
    }

    @Override
    public List<Long> selectChoiceByActivityId(Long id) {
        return activityMapper.selectChoiceByActivityId(id);
    }
}
